let Socket:any = ''
let setIntervalWesocketPush:any = null
let urlPath = ''
let num = 0
let isClsoe = false

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const closeSocket = () => {
  if (Socket !== '') {
    Socket.close()

    isClsoe = true
    clearInterval(setIntervalWesocketPush)
  }
}
export const clearIntervalWesocketPush = () => {
  clearInterval(setIntervalWesocketPush)
}
export const createSocket = (url:string) => {
  urlPath = url
  // Socket && Socket.close()
  if (!Socket) {
    Socket = new WebSocket(url)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
  }
  return Socket
}

/** 打开WS之后发送心跳 */
const onopenWS = () => {
  sendPing()
}

/** 连接失败重连 */
const onerrorWS = () => {
  num += 1
  Socket.close()

  clearInterval(setIntervalWesocketPush)
  if (num < 10 && Socket != null) {
    if (Socket.readyState !== 3) {
      Socket = null
      createSocket(urlPath)
    }
  } else {
    return null
  }
}

/** WS数据接收统一处理 */
const onmessageWS = (e:any) => {
  window.dispatchEvent(
    new CustomEvent('onmessageWS', {
      detail: {
        data: e.data
      }
    })
  )
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = (message:any) => {
  if (Socket != null) {
    setTimeout(() => {
      if (Socket.readyState === 0) {
        connecting(message)
      } else {
        Socket.send(JSON.stringify(message))
      }
    }, 1000)
  }
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = (message:any) => {
  if (Socket.readyState === 3) {
    Socket.close()
    createSocket(urlPath)
  } else if (Socket.readyState === 1) {
    Socket.send(JSON.stringify(message))
  } else if (Socket.readyState === 0) {
    connecting(message)
  } else if (Socket.readyState === 2) {
    connecting(message)
  }
}

/** 断开重连 */
const oncloseWS = () => {
  if (num < 10) {
    if (Socket.readyState !== 2) {
      Socket = null
      if (!isClsoe) {
        createSocket(urlPath)
      }
    }
  }
}
/** 发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 30000, ping = 'ping') => {
  clearInterval(setIntervalWesocketPush)
  Socket.send(ping)
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(ping)
  }, time)
}
